package HJ;

public class test2 {
    /**
     * 将一个数组升序排序后获取中位数，获取差值，x[0]-x[1]，x[1]-x[2]，x[i]-x[i+k-1]，哪个位置的数的差值跟中位数最接近
     * @param args
     */
    public static void main(String[] args) {
        int[] test = new int[] {50,50,2,3};
        System.out.println("zhongweishu:  "+ findTheStartPosition(test, 2));
    }

    public static int findTheStartPosition (int[] scores, int K) {
        // write code here
        int midNum = getMidNum(scores);
        int index = 0;
        int preReduceNum = Integer.MAX_VALUE;
        for (int i = 0; i < scores.length - 1; i++ ) {
            int num = scores[i] - scores[i+1];
            // 获取中位数和计算结果差值
            int reduceNum = getReduceNum(num, midNum);
            if (preReduceNum >= reduceNum) {
                preReduceNum = reduceNum;
                index = i;
            }
        }
        int Kindex = scores.length - 1 + K - 1;
        if (Kindex < scores.length ) {
            int num = scores[scores.length -1] - scores[Kindex];
            // 获取中位数和计算结果差值
            int reduceNum = getReduceNum(num, midNum);
            if (preReduceNum >= reduceNum) {
                index = scores.length -1;
            }
        }
        return index;
    }

    public static int getReduceNum(int num, int midNum) {
        if (num < 0) {
            num = -num;
        }
        if (midNum > num) {
            return midNum - num;
        } else{
            return num -midNum;
        }
    }

    public static int getMidNum(int[] scores) {
        int[] cloneNums = scores.clone();
        for (int i = 1; i < cloneNums.length; i ++) {
            for (int j = i ; j > 0; j--) {
                if (cloneNums[j] < cloneNums[j-1]) {
                    int temp = cloneNums[j];
                    cloneNums[j] = cloneNums[j-1];
                    cloneNums[j-1] = temp;
                }
            }
        }
        return cloneNums[cloneNums.length/2];
    }
}
